package cn.huiyunche.bms.backend.service;

import cn.huiyunche.bms.backend.bo.AdjustBO;
import cn.huiyunche.bms.backend.constant.AutoConfConstant;
import cn.huiyunche.bms.backend.query.WayBillDetailConditions;
import cn.huiyunche.bms.base.mapper.*;
import cn.huiyunche.bms.base.model.*;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.*;

@Service
public class WayBillServiceImpl implements WayBillService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WayBillServiceImpl.class);
    @Autowired
    private CWaybillMapper waybillMapper;
    @Autowired
    private AreaService areaService;
    @Autowired
    private CWaybillDetailMapper cWaybillDetailMapper;
    @Autowired
    private BmsPayableFeeDetailMapper feeDetailMapper;
    @Autowired
    private CWaybillAddressMapper addressMapper;
    @Autowired
    private CWaybillModifyLogMapper logMapper;
    @Autowired
    private AutoConfConstant autoConfConstant;
    
    @Override
    public Map<String, Object> queryWayBillByConditions(PageVo pageVo, WayBillDetailConditions conditions) throws Exception {
        LOGGER.info("WayBillServiceImpl.queryWayBillByConditions params : {}, {}", pageVo, conditions);
        Map<String, Object> map = new HashMap<>();
        String orderByClause = null;
        if (null != pageVo) {
            orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " cw.id DESC";
        }
        
        // 构建查询条件
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("bidderId", conditions.getBidderId());
        queryMap.put("status", conditions.getStatus());
        queryMap.put("departProvinceCode", conditions.getDepartProvinceCode());
        queryMap.put("departCityCode", conditions.getDepartCityCode());
        queryMap.put("departCountyCode", conditions.getDepartCountyCode());
        queryMap.put("receiptProvinceCode", conditions.getReceiptProvinceCode());
        queryMap.put("receiptCityCode", conditions.getReceiptCityCode());
        queryMap.put("receiptCountyCode", conditions.getReceiptCountyCode());
        queryMap.put("createTimeStart", conditions.getCreateTimeStart());
        queryMap.put("createTimeEnd", conditions.getCreateTimeEnd());
        if (conditions.getWayBillCodes() != null) {
            List<String> codes = Arrays.asList(conditions.getWayBillCodes().split(" "));
            queryMap.put("waybillCode", codes);
        }
        if (null != pageVo) {
            pageVo.setTotalRecord(waybillMapper.queryWayBillCountByConditions(queryMap));
            queryMap.put("limitStart", pageVo.getStartIndex());
            queryMap.put("limitEnd", pageVo.getPageSize());
            queryMap.put("orderByClause", orderByClause);
        }
        List<CWaybillDetails> list = null;
        try {
            list = waybillMapper.queryWayBillByConditions(queryMap);
        } catch (Exception e) {
            LOGGER.error("WayBillServiceImpl.queryWayBillByConditions error: {}", e);
            throw new IllegalAccessException("查询信息异常");
        }
        map.put("waybillDetailList", list);
        List<PayableFeeDetailViewDAO> nameList = null;
        try {
            nameList = cWaybillDetailMapper.selectNameByBidderId();
        } catch (Exception e) {
            LOGGER.error("WayBillServiceImpl.selectNameByBidderId error: {}", e);
            throw new IllegalAccessException("查询所有承运人异常");
        }
        map.put("carrierList", nameList);
        List<BArea> areaList = null;
        try {
            areaList = areaService.queryProvince();
        } catch (Exception e) {
            LOGGER.error("WayBillServiceImpl.queryProvince error: {}", e);
            throw new IllegalAccessException("查询区域异常");
        }
        map.put("areaList", areaList);
        if (null != pageVo) {
            map.put("page", pageVo);
        }
        return map;
    }

    @Override
    public Integer updateCost(AdjustBO bo, BindingResult br) throws Exception {
        LOGGER.info("WayBillServiceImpl.updateCost params : {}, {}", bo, br);
        if (bo.getId()==null){
            LOGGER.error("WayBillServiceImpl.updateCost：id must not be null");
            throw new IllegalArgumentException("id不能为空！");
        }else {
            BmsPayableFeeDetailExample example = new BmsPayableFeeDetailExample();
            example.createCriteria().andWaybillIdEqualTo(bo.getId().intValue());
            List<BmsPayableFeeDetail> list = feeDetailMapper.selectByExample(example);
            if (list.size()>0){
                LOGGER.error("WayBillServiceImpl.updateCost：调整失败：已生成账单的运单不能修改！");
                throw new IllegalArgumentException("调整失败：已生成账单的运单不能修改！");
            }
        }

        CWaybillModifyLog log = new CWaybillModifyLog();
        if (bo.getAftCost() != null){
            try {
                CWaybill bill = new CWaybill();
                bill.setId(bo.getId());
                bill.setCost(bo.getAftCost());
                log.setModifiedWaybillCost(bo.getAftCost());
                waybillMapper.updateByPrimaryKeySelective(bill);
            } catch (Exception e) {
                LOGGER.error("WayBillServiceImpl.updateCost：",e);
                throw new IllegalArgumentException("调整失败：调整运单表失败！");
            }
        }
        if (bo.getAftDistance() != null){
            try {
                CWaybillAddressExample example = new CWaybillAddressExample();
                example.createCriteria().andWaybillIdEqualTo(bo.getId());
                List<CWaybillAddress> list = addressMapper.selectByExample(example);
                CWaybillAddress address = new CWaybillAddress();
                address.setId(list.get(0).getId());
                address.setDistance(bo.getAftDistance());
                addressMapper.updateByPrimaryKeySelective(address);
                log.setModifiedDistance(bo.getAftDistance());
            } catch (Exception e) {
                LOGGER.error("WayBillServiceImpl.updateCost：",e);
                throw new IllegalArgumentException("调整失败：调整运单地址表失败！");
            }
        }
        log.setWaybillId(bo.getId().intValue());
        if (bo.getDistance() != null)
            log.setOldDistance(bo.getDistance());
        if (bo.getOrderCost() != null)
            log.setOldWaybillCost(bo.getOrderCost());
        if (bo.getComment() != null)
            log.setComment(bo.getComment());
        if (bo.getCreateUser() != null)
            log.setCreateUser(bo.getCreateUser());
        logMapper.insertSelective(log);
        //运单放入单据池
        CWaybill waybill = waybillMapper.selectByPrimaryKey(bo.getId());
        String url = autoConfConstant.getOperation()+ "/api/waybill/addWayBill";
        Integer time = autoConfConstant.getOperationTime();
        Map<String, Object> map = new HashMap<>();
        map.put("waybillCode", waybill.getWaybillCode());
        String result = HttpRequestUtil.sendHttpPost(url, map, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
//            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                LOGGER.error("WayBillServiceImpl addWayBill result error");
                throw new BusinessException(msgCode, msg);
            }else {
                LOGGER.info("WayBillServiceImpl addWayBill result success");
            }
        }

        return null;
    }
}
